﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Test_PLX.DataAccess;
using Test_PLX.Models;

namespace Test_PLX.Repository
{
    public class LogRepository
    {
        public List<LogModel> GetLogList(int personId)
        {
            var db = new testEntities();
            var logList = db.Log.Where(s => (personId == 0 || s.PersonId == personId))
                           .Select(s => new LogModel()
                           { LogId = s.LogId, PersonId = s.PersonId, FoodId = s.FoodId, EatTime = s.EatTime }).ToList() ;
           // var newLogList =  logList.GroupBy(s => s.PersonId) as List<LogModel>;
            return logList;
        }
        public bool AddLog(LogModel log)
        {
            var db = new testEntities();
            var addLog = new Log();
            addLog.PersonId = log.PersonId;
            addLog.FoodId = log.FoodId;
            addLog.EatTime = log.EatTime;
            db.Log.Add(addLog);
            
            if( db.Person.Where(s => s.PersonId == log.PersonId).Count()==0)
            {
                throw new Exception("添加人员不在Person表里边，没有它的id！");
            }
            if (db.Food.Where(s => s.FoodId == log.FoodId).Count() == 0)
            {
                throw new Exception("添加food不在Food表里边，没有它的id！");
            }
            return db.SaveChanges() > 0;
        }
        public bool AddPerson(PersonModel person)
        {
            var db = new testEntities();
            var addPerson = new Person();
            addPerson.PersonName = person.PersonName;
            db.Person.Add(addPerson);
            return db.SaveChanges() > 0;
        }
        public bool AddFood(FoodModel food)
        {
            var db = new testEntities();
            var addFood = new Food();
            addFood.FoodName = food.FoodName;
            db.Food.Add(addFood);
            return db.SaveChanges() > 0;
        }
        //物理删除（没有添加标志位，所以只进行了物理删除）
        public bool DeleteLog(int logId)
        {
            var db = new testEntities();
            var log = db.Log.FirstOrDefault(s => s.LogId == logId);
            db.Log.Remove(log);
            return db.SaveChanges()>0;
        }
        public bool ModifyLog(LogModel log)
        {
            var db = new testEntities();
            var log1 = db.Log.FirstOrDefault(s => s.LogId == log.LogId);
            log1.FoodId = log.FoodId;
            return db.SaveChanges()>0;
        }
    }
}